const Koa = require("koa");
const app = new Koa();
const router = require("koa-router")();
const parser = require("koa-parser");
const cors = require("koa-cors"); // 允许跨域

app.use(parser());
app.use(cors());

let arr = [
    {
      username:"马九红",
      password:123456,
      email:"123456789@qq.com",
      sex:"女",
      hobby:"羽毛球"
    },
    {
      username:"邓慧颖",
      password:123456,
      email:"123456789@qq.com",
      sex:"女",
      hobby:"足球"
    },
    {
      username:"周秋月",
      password:123456,
      email:"123456789@qq.com",
      sex:"女",
      hobby:"篮球-乒乓球"
    },
    {
      username:"刘佳文",
      password:123456,
      email:"123456789@qq.com",
      sex:"男",
      hobby:"篮球-羽毛球"
    },
    {
      username:"王佳伟",
      password:123456,
      email:"123456789@qq.com",
      sex:"男",
      hobby:"足球-台球"
    }
];

router.get("/usr",async ctx=>{
    ctx.body = arr;
})
router.post("/usr",async ctx=>{
    let da = ctx.request.body.data;
    console.log(da)
    arr.push(da);
    ctx.body = true;
})
router.delete("/usr/:index",async ctx=>{
    let ind = ctx.params.index;
    arr.splice(ind,1);
    ctx.body = true;
})

router.put("/usr/:index",async ctx=>{
    let ind = ctx.params.index;
    let setUsr = ctx.request.body.usr;
    console.log(setUsr);
    arr.splice(ind,1,setUsr);
    ctx.body = true;
})
router.get("/getMod/:index",async ctx=>{
  let ind = ctx.params.index;
  let tempUsr;
  for(let i=0;i<arr.length;i++){
    if(ind == i){
      tempUsr = arr[i]
    }
  }
  ctx.body = tempUsr;
})

app.use(router.routes());
app.listen("3000",()=>{
    console.log("running 3000");
})